import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/',
      redirect: '/servers'
    },
    {
      path: '/servers',
      name: 'ServerList',
      component: () => import('@/views/ServerList.vue'),
      meta: { title: '服务器', requiresAuth: true, keepAlive: true }
    },
    {
      path: '/terminal/:serverId',
      name: 'Terminal',
      component: () => import('@/views/Terminal.vue'),
      meta: { title: '终端', requiresAuth: true }
    },
    {
      path: '/monitor/:serverId',
      name: 'Monitor',
      component: () => import('@/views/Monitor.vue'),
      meta: { title: '监控', requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('@/views/Profile.vue'),
      meta: { title: '我的', requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 老薛SSH工具` : '老薛SSH工具'
  
  console.log('📱 路由:', from.path, '→', to.path)
  console.log('🔍 认证状态:', {
    token: authStore.token ? '已设置' : '未设置',
    user: authStore.user ? authStore.user.username : '无',
    isAuthenticated: authStore.isAuthenticated
  })
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    console.log('⚠️  未登录，跳转登录页')
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    console.log('✅ 已登录，跳转服务器列表')
    next('/servers')
  } else {
    next()
  }
})

export default router

